﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using ClassModel;
using ClassBLL;
using ClassCommon;
using System.Security.Cryptography;

namespace ClassWeb.Controllers
{
    public class FindPasswordController : Controller
    {
        //
        // GET: /FindPassword/
        // 找回密码首页
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FindPassword(
                string userAccount,
                string code, // 验证码
                string phoneValidateCode// 手机验证码
            )
        {
            /*
             userAccount --- 18571656584
Index:201 code --- 1145
Index:201 phoneValidateCode --- 5842
             */
            this.Response.ContentType = "application/json";

            userAccount = userAccount.Trim();
            code = code.Trim();
            phoneValidateCode = phoneValidateCode.Trim();

            #region 服务端验证

            // 验证账号是否为空
            if (string.IsNullOrEmpty(userAccount))
                return Json(new
                {
                    status = false,
                    info = "账号不能为空!",
                    cls = "userAccount"
                }, JsonRequestBehavior.AllowGet);

            // 验证账号是否存在
            if (!t_classDemo_UserInfo_BLL.checkUserExists(userAccount))
                return Json(new
                {
                    status = false,
                    info = "当前账号不存在",
                    cls = "userAccount"
                }, JsonRequestBehavior.AllowGet);

            // 验证验证码是否正确
            string normalCode = HttpCookieHelper.getValidateCode();
            if (code.ToLower() != normalCode.ToLower())
                return Json(new
                {
                    status = false,
                    info = "验证码错误!",
                    cls = "catchaCode"
                },
                    JsonRequestBehavior.AllowGet);

            var isPhoneFindPassWord = false;
            // 检测手机验证码是否正确
            if (RegexHelper.isPhoneNum(userAccount))
            {
                if (phoneValidateCode != HttpCookieHelper.getPhoneValidateCode())
                {
                    return Json(new
                    {
                        status = false,
                        info = "手机验证码错误!",
                        cls = "phoneValidateCode"
                    },
                        JsonRequestBehavior.AllowGet);
                }
                isPhoneFindPassWord = true;
            }
            #endregion


            // 格式 = account&datetime
            string tokenFormat = string.Format("{0}&{1}", userAccount, DateTime.Now);
            string encodeToken = EncryptHelper.Encrypt(tokenFormat);
            t_class_findpassword_token tokenModel = new t_class_findpassword_token();
            tokenModel.token = encodeToken;
            tokenModel.createtime = DateTime.Now;

            t_class_FindPassword_BLL.InsertToken(tokenModel);

            //混淆
            string mixTokenKey = Guid.NewGuid().ToString().ToUpper()
                                                          .Replace("-", string.Empty);

            string mixTokenValue = Guid.NewGuid().ToString().ToLower()
                                    + Guid.NewGuid().ToString().ToLower()
                                    + Guid.NewGuid().ToString().ToLower()
                                    + Guid.NewGuid().ToString().ToLower();

            mixTokenValue = mixTokenValue.Replace("-", string.Empty);

            string findLink = "/FindPassword/ChangePassword?token=" + tokenModel.token + "&" + mixTokenKey + "=" + mixTokenValue;

            if (isPhoneFindPassWord)
            {
                // 如果是手机号码密码找回.// 设置下一步的链接
                return Json(new { status = true, info = findLink }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                // string htmlBody = ........
                // EmailHelper.sendFindPasswordEmail(xxx,xxxx,htmlBody);
                // 邮箱找到，设置下一步的链接。 // 跳转到发送邮件提示页面
                // string href = GetEmailLink(userAccount); //163 qq sina .......

                string emailBody = EmailHelper.GetEmailBody(findLink, userAccount);

                // 发送邮件
                EmailHelper.Send(userAccount, ConfigSetting.Mail_Subject, emailBody);

                string href = EmailHelper.GetEmailLink(userAccount);

                return Json(new
                {
                    status = true,
                    info = "/tip.html?userAccount=" + userAccount + "&emailLink=" + href + "&t=e"
                }, JsonRequestBehavior.AllowGet);
            }
        }


        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ChangePassword(string token)
        {
            if (string.IsNullOrEmpty(token)) { return Redirect("/home"); }

            // 检查token的合法性
            if (!t_class_FindPassword_BLL.isTokenExists(token))
            {
                // token 不存在
                return Redirect("/tip.html?t=t&fs=f");
            }

            ViewBag.token = token;

            return View();
        }

        /// <summary>
        /// 修改密码post提交。
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="password">新密码</param>
        /// <param name="confirmPassword">重复新密码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangePassword(
            string token,
            string password,
            string confirmPassword
            )
        {
            // this.Response.ContentType = "application/json";

            #region 服务端验证

            if (string.IsNullOrEmpty(token))
                return Json(new { status = false, info = "token不存在" }, JsonRequestBehavior.AllowGet);

            if (string.IsNullOrEmpty(password))
                return Json(new { status = false, info = "密码不能为空!" }, JsonRequestBehavior.AllowGet);

            if (password != confirmPassword)
                return Json(new { status = false, info = "两次密码不一致!" }, JsonRequestBehavior.AllowGet);

            #endregion

            try
            {
                // 解密token
                string decodeToken = EncryptHelper.Decrypt(token);
                string[] array = decodeToken.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                // 拿到用户账户
                string userAccount = array[0];
                // 拿到事件戳
                string datetime = array[1];

                DateTime tokenTime = Convert.ToDateTime(datetime);
                DateTime now = DateTime.Now;
                TimeSpan span = now - tokenTime;
                if (span.TotalDays > 1)
                {
                    // token失效。
                    // 删除此token
                    t_class_FindPassword_BLL.deleteToken(token);

                    return Json(new { status = false, info = "token已经失效，请重新找回密码!" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    //开始修改密码
                    bool result = t_classDemo_UserInfo_BLL.UpdatePassword(password, userAccount);
                    // 删除已找回密码的token
                    t_class_FindPassword_BLL.deleteToken(token);
                    return Json(new { status = result, info = "密码修改成功!" });
                }
            }
            catch (Exception ex)
            {
                // 参数解析错误!

                ViewBag.errorMsg = "token格式无效!";

                return Json(new { status = false, info = "token解析失败!" }, JsonRequestBehavior.AllowGet);
            }
        }




        /// <summary>
        /// emailFindPasswordView
        /// </summary>
        /// <returns></returns>
        public ActionResult EmailFindPwView(string userAccount)
        {
            return View();
        }

        /// <summary>
        /// 邮件内容视图 - 复制粘贴
        /// </summary>
        /// <returns></returns>
        public ActionResult EmailContentView()
        {
            return View();
        }
    }
}
